#!/usr/bin/perl

package mod_db;

use strict;
use Exporter;
use Fcntl ':flock';
use IO::Handle;

our ( $VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS );

$VERSION     = 1.00;
@ISA         = qw( Exporter );
@EXPORT      = qw( &db_store &db_exists &db_init );

our $db_file_name = undef;
our %db = ( );

sub db_init($)
{
	$db_file_name = shift;

	open( DB, "+>> $db_file_name" ) or die "error: db_init: open: $!\n";
	DB -> autoflush( 1 );

	seek( DB, 0, 0 );
	my @db_keys = grep { $_ !~ /^\s*$/ } <DB>;
	chomp for @db_keys;
	@db{ @db_keys } = (1) x @db_keys;
}

sub db_store($)
{
	defined $db_file_name or die "error: db_store: call db_init( 'database' ) first\n";

	my $key = shift;
	$key =~ s/\r?\n/[\\n]/g;

	return if db_exists( $key );

	flock( DB, LOCK_EX ) or die "error: db_store: flock failed: $!\n";
	seek( DB, 0, 2 );
	print DB "$key\n";
	flock( DB, LOCK_UN ) or die "error: db_store: flock failed: $!\n";

	$db{$key} = 1;
	
}

sub db_exists($)
{
	defined $db_file_name or die "error: db_store: call db_init( 'database' ) first\n";

	my $key = shift;
	$key =~ s/\r?\n/[\\n]/g;

	exists $db{$key};
}

1;
